<template>
  <el-container class="book-detail">
    <!-- 图书封面和信息展示 -->
    <el-card class="book-info-card">
      <el-row :gutter="20">
        <el-col :span="8">
          <!-- 图书封面 -->
          <div class="book-cover-container">
            <img :src="getImageUrl(book.bookCover)" alt="封面" class="book-cover" />
          </div>
        </el-col>
        <el-col :span="16">
          <!-- 图书信息展示 -->
          <el-row :gutter="10">
            <el-col :span="24">
              <h1 class="book-title">{{ book.bookName }}</h1>
            </el-col>
            <el-col :span="12">
              <p class="book-number">编号: {{ book.bookNumber }}</p>
            </el-col>
            <el-col :span="12">
              <p class="book-bookArea">位置: {{ book.bookArea + book.bookLocation + "架" }}</p>
            </el-col>
            <el-col :span="12">
              <p class="book-category">分类: {{ book.bookType }}</p>
            </el-col>
            <el-col :span="12">
              <p class="book-author">作者: {{ book.bookAuthor }}</p>
            </el-col>
            <el-col :span="24">
              <el-text class="book-description">{{ book.bookDescription }}</el-text>
            </el-col>
            <el-col :span="24">
              <!-- 借阅功能 -->
              <el-button
                type="primary"
                size="large"
                :loading="isBorrowing"
                :disabled="isBorrowed"
                @click="borrowBook"
                class="borrow-button"
              >
                {{ isBorrowed ? "已借出" : "借阅" }}
              </el-button>
            </el-col>
          </el-row>
        </el-col>
      </el-row>
    </el-card>

    <!-- 随机推荐书籍部分 -->
    <section class="hot-books">
      <h2>随机推荐书籍</h2>
      <el-row :gutter="20">
        <el-col :span="4" v-for="(book, index) in randomBooks" :key="index">
          <el-card :body-style="{ padding: '20px' }" class="recommend-book-card" @click="goToBookDetail(book.bookNumber)">
            <div class="book-cover-container">
              <el-image :src="getImageUrl(book.bookCover)" alt="封面" class="book-cover" />
            </div>
            <el-link class="book-name">{{ book.bookName }}</el-link>
            <p class="author">作者: {{ book.bookAuthor }}</p>
            <el-text class="description">{{ book.bookDescription }}</el-text>
          </el-card>
        </el-col>
      </el-row>
    </section>
  </el-container>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import http from '../utils/axios.js';
import { ElMessage } from "element-plus";

const route = useRoute();
const router = useRouter();
const book = ref({});
const isBorrowed = ref(false);
const isBorrowing = ref(false);
const randomBooks = ref([]);  // 随机推荐书籍

// 从路由参数获取图书编号
const bookNumber = route.params.bookNumber;

// 获取图书详情
const fetchBookDetails = async (bookNum = bookNumber) => {
  try {
    const response = await http.get(`/book/${bookNum}`);
    book.value = response.data;
    isBorrowed.value = response.data.bookStatus === '已借出';
  } catch (error) {
    console.error('获取图书详情失败:', error);
    await router.push('/'); // 如果获取失败返回首页
  }
};

// 监听路由变化
watch(
  () => route.params.bookNumber,
  (newBookNumber) => {
    fetchBookDetails(newBookNumber); // 使用新的图书编号获取详情
    fetchRandomBooks(); // 刷新随机推荐书籍
  }
);

// 获取随机推荐书籍
const fetchRandomBooks = async () => {
  try {
    const response = await http.get('/home/randomBook', { params: { limit: 30 } });
    randomBooks.value = response.data && Array.isArray(response.data) ? response.data : [];
  } catch (error) {
    console.error('获取随机推荐书籍时出错:', error);
  }
};

// 借阅图书
const borrowBook = async () => {
  isBorrowing.value = true;
  try {
    if (!localStorage.getItem('cardNumber')) {
      ElMessage.error('请先登录借阅账户！');
      return;
    }
    const payload = {
      cardNumber: localStorage.getItem('cardNumber'), // 从用户信息中获取
      bookNumber: bookNumber,
    };
    await http.post('/borrow/lend', payload);
    isBorrowed.value = true;
    ElMessage.success('借阅成功！');
  } catch (error) {
    console.error('借阅失败:', error);
    ElMessage.error('借阅失败，请稍后重试！');
  } finally {
    isBorrowing.value = false;
  }
};

// 跳转到图书详情页
const goToBookDetail = (bookNumber) => {
  router.push(`/book/${bookNumber}`);
};

// 页面加载时获取数据
onMounted(() => {
  fetchBookDetails();
  fetchRandomBooks();
});

// 获取图书封面 URL
const getImageUrl = (coverName) => {
  if (coverName) {
    return `http://localhost:8080/book/image/${coverName}?t=${new Date().getTime()}`;
  }
  return 'http://localhost:8080/book/image/null.jpg'; // 如果没有封面，则返回空字符串
};
</script>

<style scoped>
/* 全局样式 */
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  font-family: Arial, sans-serif;
  background-color: #f9f9f9;
}

img {
  width: 100%;
  height: auto;
}

h1 {
  font-size: 32px;
  color: #333;
  margin-bottom: 20px; /* 添加行间距 */
}

h2, h3, h4 {
  color: #333;
  margin-bottom: 20px; /* 添加行间距 */
}

.new-books h2 {
  font-size: 24px;
  margin-bottom: 20px;
}

/* 随机推荐书籍部分样式 */
.hot-books {
  margin-top: 40px;
}

.hot-books h2 {
  font-size: 24px;
  margin-bottom: 20px;
}

.book-cover {
  max-width: 100%;
  height: 300px; /* 设置封面图片的固定高度 */
  object-fit: contain; /* 锁定纵横比，不裁剪 */
}

/* 描述样式 */
.description {
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  overflow: hidden;
  text-overflow: ellipsis;
  margin-bottom: 10px; /* 添加行间距 */
}

/* 书名样式 */
.book-name {
  white-space: nowrap; /* 防止文本换行 */
  font-size: 21px;
  font-weight: bold;
  overflow: hidden;    /* 隐藏溢出的文本 */
  text-overflow: ellipsis; /* 使用省略号表示被隐藏的文本 */
  width: 100%;         /* 确保元素有宽度限制 */
  margin-bottom: 10px; /* 添加行间距 */
}

/* 作者样式 */
.author {
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 1;
  line-clamp: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  margin-bottom: 10px; /* 添加行间距 */
}

/* 书籍封面容器样式 */
.book-cover-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%; /* 确保封面容器高度与信息容器一致 */
}

/* 书籍信息容器样式 */

/* 书籍详情页面样式 */
.book-detail {
  padding: 20px;
  display: flex;
  justify-content: center;
  align-items: flex-start;
  min-height: 100vh;
  flex-wrap: wrap; /* 允许换行 */
  background-image: url('../assets/images/background.jpg');
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
}

.book-info-card {
  flex: 1;
}

.borrow-button {
  width: 300px; /* 设置按钮宽度 */
  height: 50px; /* 设置按钮高度 */
  margin-top: 20px; /* 添加按钮的上间距 */
}

/* 图书信息中的每个部分样式 */
.book-number, .book-bookArea, .book-category, .book-author {
  margin-bottom: 20px; /* 添加行间距 */
}

.book-description {
  margin-bottom: 20px; /* 添加行间距 */
}

/* 推荐书籍卡片样式 */
.recommend-book-card {
  cursor: pointer;
  transition: transform 0.2s;
}

.recommend-book-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.recommend-book-card .book-cover-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 150px; /* 设置封面图片的固定高度 */
}

.recommend-book-card .book-cover {
  max-width: 100%;
  height: 100%; /* 使图片高度占满容器 */
  object-fit: contain; /* 保持图片比例，完全显示 */
  border-radius: 4px; /* 添加圆角 */
}

.recommend-book-card .book-name {
  font-size: 18px;
  margin-top: 10px;
}

.recommend-book-card .author {
  font-size: 14px;
  color: #666;
}

.recommend-book-card .description {
  font-size: 14px;
  color: #999;
}

/* el-row 和 el-col 的间距 */
.el-row {
  margin-bottom: 20px; /* 添加行间距 */
}

.el-col {
  margin-bottom: 20px; /* 添加列间距 */
}
</style>
